package com.cuanbobox.tcp.wds;

import com.cuanbobox.base.App;
import com.cuanbobox.bean.DataList;
import com.cuanbobox.bean.WdsDataList;
import com.cuanbobox.utils.LogUtil;

import java.io.IOException;
import java.io.OutputStream;

/**
 * 给矩阵发送消息的线程
 */
public class WindowsSendThread extends Thread {
    private WindowsInitThread tcpInitThread;
    private OutputStream output;
    public static Object lock = new Object();
    private boolean loop;

    public WindowsSendThread(WindowsInitThread tcpInitThread) {
        this.tcpInitThread = tcpInitThread;
        try {
            output = tcpInitThread.getSocket().getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        super.run();
        loop = true;
        LogUtil.add("发送", "启动发送线程-->" + Thread.currentThread().getName(), "互动TCP");
        while (App.running && loop) {
            try {
                String strData = WdsDataList.get();
                if (strData != null) {
                    LogUtil.add("发送", ""+strData, "互动TCP");
                    output.write(strData.getBytes("utf-8"));
                    output.flush();
                }
                Thread.sleep(10);
            } catch (Exception e) {
                LogUtil.addError("---------------WindowsReceiveThread异常-----------------");
                LogUtil.addError(e);
                LogUtil.addError("---------------end-----------------");
                tcpInitThread.close();
            }
        }
        try {
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        LogUtil.add("发送", "关闭发送线程-->" + Thread.currentThread().getName(), "互动TCP");
    }

    public void stopThread() {
        loop = false;
    }
}
